package com.example.junit5demo;

import com.example.junit5demo.domain.User;
import com.example.junit5demo.service.ServiceA;
import com.example.junit5demo.service.ServiceB;
import com.example.junit5demo.service.ServiceC;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.util.ReflectionTestUtils;

import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.when;

@SpringBootTest
public class MockitoTest_Mock {
    private static final Logger log = LoggerFactory.getLogger(Junit5DemoApplicationTests.class);

    //需要mock注入的服务
    @InjectMocks
    @Autowired
    private ServiceA serviceA;

    //需要mock注入的服务
    @InjectMocks
    @Autowired
    private ServiceB serviceB;

    //需要mock掉的服务
    @Mock
    @Autowired
    private ServiceC serviceC;

    //初始化mock注入
    @BeforeEach
    public void initMock() {
        MockitoAnnotations.initMocks(this);
        ReflectionTestUtils.setField(serviceB,"serviceC",serviceC);
    }

    @Test
    public void test() {
        User user = new User();
        user.setId(111);
        user.setName("张三");

        //mock掉ServiceC的getUser()方法，返回指定的user对象
        when(serviceC.getUser(anyInt())).thenReturn(user);


        //调用需要测试的方法，结果将是mock结果
        User userVo = serviceA.getUserVo(123);

        log.info(userVo.toString());
    }
}



